package com.siemens.industrial.web.mvc.controller.partner.user;

import com.siemens.industrial.model.admin.SystemConfig;
import com.siemens.industrial.model.partner.Metadata;
import com.siemens.industrial.model.partner.Device;
import com.siemens.industrial.model.partner.User;
import com.siemens.industrial.utils.GlobalResponseCode;
import com.siemens.industrial.utils.RestResponse;
import com.siemens.industrial.utils.SiemensException;
import com.siemens.industrial.utils.UUIDGenerator;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import com.siemens.industrial.web.mvc.service.AuthService;
import com.siemens.industrial.web.mvc.service.WriteLogs;
import com.siemens.industrial.web.mvc.service.admin.TenantService;
import com.siemens.industrial.web.mvc.service.partner.PartnerDeviceService;
import com.siemens.industrial.web.mvc.service.partner.PartnerMetadataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/10/17.
 */
@Controller
public class PartnerDeviceController {
    @Resource
    PartnerDeviceService partnerDeviceService;

    @Resource
    TenantService tenantService;

    @Resource
    PartnerMetadataService partnerMetadataService;

    @Resource
    WriteLogs writeLogs;

    @Resource
    AuthService authService;

    @RequestMapping(value = "/partner/{tenant}/tenant/device/info", method = RequestMethod.GET)
    public String getDeviceInfoPage(@PathVariable("tenant") String tenantKey,
                                    ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        modelMap.put("key", tenantKey);
        return "partner/user/device_info";
    }

    @RequestMapping(value = "/partner/{tenant}/planDowntime/list", method = RequestMethod.GET)
    public String getDevicePlanDowntime(@PathVariable("tenant") String tenantKey,
                                        String deviceId,
                                        ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        modelMap.put("deviceId", deviceId);
        modelMap.put("key", tenantKey);
        return "partner/user/plan_downtime_list";
    }

    @RequestMapping(value = "/partner/{tenant}/tenant/api/v1/device/info", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getDeviceInfo(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Device> list = partnerDeviceService.getDeviceList(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/api/v1/{tenant}/tenant/device/device", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> deleteEvent(@PathVariable("tenant") String tenantKey, @RequestParam(name = "deviceId") String deviceId) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Device device = partnerDeviceService.getDeviceById(tenantId, deviceId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(device).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/getByUniqueId", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getDevice(@PathVariable("tenant") String tenantKey, @RequestParam(name = "uniqueId") String uniqueId) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Device device = partnerDeviceService.getDeviceByUniqueId(tenantId, uniqueId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(device).build();
    }

    @RequestMapping(value = "/partner/{tenant}/tenant/device/create", method = RequestMethod.GET)
    public String getCreatePage(@PathVariable("tenant") String tenantKey, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Metadata> metadataList = partnerMetadataService.getAllByKey(tenantId, "MachineNumber");
        modelMap.put("key", tenantKey);
        modelMap.put("machines", metadataList);
        return "/partner/user/createDevice";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/getMeta", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMeta(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Metadata> metadataList = partnerMetadataService.getAllByKey(tenantId, "MachineNumber");
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(metadataList).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/getMetaType", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMetaType(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<String> models = partnerMetadataService.getMetaType(tenantId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(models).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/getMetaModel", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMetaModel(@PathVariable("tenant") String tenantKey, String type) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<String> models = partnerMetadataService.getMetaModel(tenantId, type);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(models).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getMetaModel(@PathVariable("tenant") String tenantKey,
                                            @RequestBody Map<String, Object> data) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        try {
            String deviceId = UUIDGenerator.getUUID();
            partnerDeviceService.saveDevice(tenantId, data, deviceId);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            Device device = partnerDeviceService.getDeviceById(tenantId, deviceId);
            String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "创建了机床" + "\"" + device.getDeviceUniqueId() + "\"的信息";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, tenantKey + "_operate");
            return RestResponse.create(GlobalResponseCode.SUCCESS).build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return RestResponse.create(GlobalResponseCode.SUCCESS).build();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/devices", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getDevices(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> deviceList = partnerDeviceService.getDevices(tenantId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(deviceList).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/MTIDS", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMtIds(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Device> deviceList = partnerDeviceService.getAll(tenantId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(deviceList).build();
    }

    @RequestMapping(value = "/partner/{tenant}/device/devices", method = RequestMethod.GET)
    public String getDevicesPage(@PathVariable("tenant") String tenantKey, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("key", tenantKey);
        return "/partner/user/device_list";
    }

    @RequestMapping(value = "/partner/{tenant}/device/edit", method = RequestMethod.GET)
    public String getDevicesEditPage(@PathVariable("tenant") String tenantKey, @RequestParam(name = "deviceId", required = true) String deviceId, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Device device = partnerDeviceService.getDevice(tenantId, deviceId);
        modelMap.put("device", device);
        modelMap.put("key", tenantKey);
        return "/partner/user/device_edit";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/edit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateDevice(@PathVariable("tenant") String tenantKey, @RequestBody Map<String, Object> data) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        try {
            partnerDeviceService.updateDevice(tenantId, data);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            Device device = partnerDeviceService.getDeviceById(tenantId, data.get("deviceId").toString());
            String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "更新了机床" + "\"" + device.getDeviceUniqueId() + "\"的信息";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, tenantKey + "_operate");

            return RestResponse.create(GlobalResponseCode.SUCCESS).build();
        } catch (SiemensException e) {
            return RestResponse.create(e).build();
        }

    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteDevice(@PathVariable("tenant") String tenantKey, @RequestParam(name = "deviceId") String deviceId) throws SiemensException {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerDeviceService.deleteDevice(tenantId, deviceId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        User currentUser = (User) authService.currentUser();
        Device device = partnerDeviceService.getDeviceById(tenantId, deviceId);
        String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "删除了机床" + "\"" + device.getDeviceUniqueId() + "\"。";
        writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, tenantKey + "_operate");
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/device/getDashboder", method = RequestMethod.GET)
    public String getdashbord(@PathVariable("tenant") String tenantKey, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("key", tenantKey);
        return "test";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/getChartHeaders", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getChartHeadersData(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        Map<String, Object> map = partnerDeviceService.getChartForHeader(tenantId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(map).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/search", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getChartSearchData(@PathVariable("tenant") String tenantKey,
                                                  @RequestBody Map<String, Object> map) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        String model = map.get("model").toString();
        String type = map.get("type").toString();
        String group = map.get("group").toString();
        String line = map.get("line").toString();
        List<Map<String, Object>> list = partnerDeviceService.getAllMtInfo(tenantId, model, type, group, line);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/linesAndGroups", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getChartSearchData(@PathVariable("tenant") String tenantKey,
                                                  String type, String model) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Map<String, Object> map = partnerDeviceService.getLinesAndGroupsMtInfo(tenantId, type, model);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(map).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/saddaadad", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> ssdsafasf(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        partnerDeviceService.adadadasd(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/like", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMTIdLike(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllMTIdsLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/message/like", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getIdleLike(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllIdleLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/devicesByDataTable", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getDevicesByDataTable(@PathVariable("tenant") String tenantKey,
                                                     HttpServletRequest request) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        DataTableQuery dt = new DataTableQuery(request);

        if (dt.isDataTableRequest()) {
            Map<String, Object> deviceList = partnerDeviceService.getDevicesByDataTable(tenantId, request);
            return deviceList;
        }
        return dt.buildResponse(0, 0, new ArrayList<>());
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/message/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateStatus(@PathVariable("tenant") String tenantKey,
                                            @RequestBody Map<String,Object> map){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        User user = (User) authService.currentUser();
        partnerDeviceService.updateStatus(tenantId,map,user.getUserId());
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/likeName", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getNameLike(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllMTNamesLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/likeType", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTypeLike(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllMTTypesLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/likeModel", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getModelLike(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllMTModelsLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/likeGroup", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getGroupLike(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllMTGroupsLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/likeLine", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getNameLine(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllMTLinesLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/likeMade", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMadeLike(@PathVariable("tenant") String tenantKey, String str) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerDeviceService.getAllMTMadesLike(tenantId, str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/searchInfo", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMadeLike(@PathVariable("tenant") String tenantKey,
                                           @RequestParam(name ="mtid" ,required = false) String mtid,
                                           @RequestParam(name ="type" ,required = false) String type,
                                           @RequestParam(name ="model" ,required = false) String model,
                                           @RequestParam(name ="name" ,required = false) String name,
                                           @RequestParam(name ="group" ,required = false) String group,
                                           @RequestParam(name ="line" ,required = false) String line,
                                           @RequestParam(name = "made",required = false)String made) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Device> list = partnerDeviceService.getAllDeviceSearchInfo(tenantId,mtid,type,model,name,group,line,made);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/searchInfoByDateTable", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMadeLikeByDateTable(@PathVariable("tenant") String tenantKey,
                                           @RequestParam(name ="mtid" ,required = false) String mtid,
                                           @RequestParam(name ="type" ,required = false) String type,
                                           @RequestParam(name ="model" ,required = false) String model,
                                           @RequestParam(name ="name" ,required = false) String name,
                                           @RequestParam(name ="group" ,required = false) String group,
                                           @RequestParam(name ="line" ,required = false) String line,
                                           @RequestParam(name = "made",required = false)String made,
                                                      HttpServletRequest request) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        DataTableQuery dt = new DataTableQuery(request);

        if(dt.isDataTableRequest()){
            Map<String,Object> map = partnerDeviceService.getDeviceSearchByDateTable(tenantId,mtid,type,model,name,group,line,made,request);
            return map;
        }
        return dt.buildResponse(0, 0, new ArrayList<>());
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/device/exportDeviceXml", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> exportDeviceXml(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        try {
            String name = partnerDeviceService.startExportXml(tenantId);
            return RestResponse.create(GlobalResponseCode.SUCCESS).putData(name).build();

        } catch (IOException e) {
            e.printStackTrace();
            return RestResponse.create(GlobalResponseCode.ERROR_EXPORT_FILE_FAIL).build();
        }
    }
}